<template>
  <div class="project-list-container">
    <div class="content full-width">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else class="projects-grid">
        <el-row :gutter="20">
          <!-- 添加创建项目卡片 -->
          <el-col 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
            class="project-col"
          >
            <el-card 
              class="project-card create-project-card" 
              @click="goToCreateProject"
              shadow="hover"
            >
              <div class="create-card-content">
                <el-icon class="add-icon"><Plus /></el-icon>
                <h3>创建新项目</h3>
                <p>添加一个新的API监控项目</p>
              </div>
            </el-card>
          </el-col>
          
          <!-- 空状态处理 -->
          <div v-if="projects.length === 0" class="empty-container">
            <el-empty description="暂无项目">
              <el-button type="primary" @click="goToCreateProject">创建项目</el-button>
            </el-empty>
          </div>
          
          <!-- 项目列表 -->
          <template v-else>
            <el-col 
              v-for="project in projects" 
              :key="project.id" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
              class="project-col"
            >
              <el-card 
                class="project-card" 
                @click="viewProject(project)"
                shadow="hover"
              >
                <div class="card-content">
                  <div class="project-header">
                    <el-avatar 
                      :size="40" 
                      :src="project.iconUrl" 
                      v-if="project.iconUrl" 
                      shape="square"
                      class="project-avatar"
                    />
                    <el-avatar 
                      :size="40" 
                      v-else 
                      shape="square"
                      class="project-avatar default-avatar"
                    >
                      {{ project.name?.charAt(0).toUpperCase() }}
                    </el-avatar>
                    <div class="project-info">
                      <h3 class="project-name">{{ project.name }}</h3>
                      <p class="project-description" v-if="project.description">
                        {{ project.description }}
                      </p>
                    </div>
                  </div>

                  <div class="project-stats">
                    <div class="stat-item">
                      <el-icon><Connection /></el-icon>
                      <span>{{ project.endpointCount || 0 }} 接口</span>
                    </div>
                    <div class="stat-item">
                      <el-icon><Clock /></el-icon>
                      <span>{{ formatDate(project.updatedAt) }}</span>
                    </div>
                  </div>

                  <div class="project-footer">
                    <el-tag 
                      :type="project.status === 'active' ? 'success' : 'info'"
                      size="small"
                    >
                      {{ project.status === 'active' ? '活跃' : '非活跃' }}
                    </el-tag>
                    <el-dropdown @command="handleProjectAction" class="more-actions">
                      <el-button type="primary" size="small" link>
                        <el-icon><More /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{action: 'edit', project}">
                            <el-icon><Edit /></el-icon>
                            编辑
                          </el-dropdown-item>
                          <el-dropdown-item :command="{action: 'delete', project}" divided>
                            <el-icon><Delete /></el-icon>
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </el-card>
            </el-col>
          </template>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Folder, 
  Plus, 
  More, 
  Edit, 
  Delete, 
  Connection, 
  Clock 
} from '@element-plus/icons-vue'
import api from '../services/api'

console.log('ProjectList.vue 模块开始加载 at:', new Date().toISOString())

export default {
  name: 'ProjectList',
  components: {
    Folder,
    Plus,
    More,
    Edit,
    Delete,
    Connection,
    Clock
  },
  setup() {
    console.log('ProjectList 组件初始化 at:', new Date().toISOString())
    const router = useRouter()
    const projects = ref([])
    const loading = ref(false)
    
    // 获取项目列表
    const fetchProjects = async () => {
      console.log('开始获取项目列表 at:', new Date().toISOString())
      loading.value = true
      try {
        const startTime = Date.now()
        const response = await api.get('/projects')
        const endTime = Date.now()
        console.log(`API请求耗时: ${endTime - startTime}ms`)
        
        // 检查响应数据结构，确保有data属性且为数组
        // 现在后端使用ResponseEntity包装数据，实际数据在response.data中
        if (response && response.data && Array.isArray(response.data)) {
          projects.value = response.data.map(project => ({
            ...project,
            endpointCount: project.endpointCount || 0,
            status: project.status || 'active'
          }))
        } else if (response && Array.isArray(response)) {
          projects.value = response.map(project => ({
            ...project,
            endpointCount: project.endpointCount || 0,
            status: project.status || 'active'
          }))
        } else {
          // 如果响应不是预期格式，使用模拟数据
          console.warn('API响应格式不符合预期:', response)
          projects.value = [
            {
              id: 1,
              name: '电商平台API',
              description: '电商平台后端服务接口',
              createdAt: '2023-01-15T10:30:00Z',
              updatedAt: '2023-06-20T14:20:00Z',
              endpointCount: 15,
              status: 'active'
            },
            {
              id: 2,
              name: '用户管理系统',
              description: '用户认证和权限管理服务',
              createdAt: '2023-02-10T09:15:00Z',
              updatedAt: '2023-06-18T16:45:00Z',
              endpointCount: 8,
              status: 'active'
            },
            {
              id: 3,
              name: '数据分析服务',
              description: '大数据分析和报表服务',
              createdAt: '2023-03-05T11:20:00Z',
              updatedAt: '2023-05-10T09:30:00Z',
              endpointCount: 12,
              status: 'inactive'
            }
          ]
        }
      } catch (error) {
        ElMessage.error('获取项目列表失败: ' + error.message)
        // 使用模拟数据以便展示
        projects.value = [
          {
            id: 1,
            name: '电商平台API',
            description: '电商平台后端服务接口',
            createdAt: '2023-01-15T10:30:00Z',
            updatedAt: '2023-06-20T14:20:00Z',
            endpointCount: 15,
            status: 'active'
          },
          {
            id: 2,
            name: '用户管理系统',
            description: '用户认证和权限管理服务',
            createdAt: '2023-02-10T09:15:00Z',
            updatedAt: '2023-06-18T16:45:00Z',
            endpointCount: 8,
            status: 'active'
          },
          {
            id: 3,
            name: '数据分析服务',
            description: '大数据分析和报表服务',
            createdAt: '2023-03-05T11:20:00Z',
            updatedAt: '2023-05-10T09:30:00Z',
            endpointCount: 12,
            status: 'inactive'
          }
        ]
      } finally {
        loading.value = false
        console.log('项目列表获取完成 at:', new Date().toISOString())
      }
    }
    
    // 跳转到创建项目页面
    const goToCreateProject = () => {
      router.push('/project/create')
    }
    
    // 查看项目详情
    const viewProject = (project) => {
      // 直接跳转到接口监控页面，而不是项目详情页
      router.push(`/project/${project.id}/endpoints`)
    }
    
    // 处理项目操作
    const handleProjectAction = (command) => {
      const { action, project } = command
      switch (action) {
        case 'edit':
          // 跳转到编辑页面
          router.push(`/project/${project.id}/edit`)
          break
        case 'delete':
          deleteProject(project)
          break
      }
    }
    
    // 删除项目
    const deleteProject = (project) => {
      ElMessageBox.confirm(
        `确定要删除项目 "${project.name}" 吗？此操作不可恢复。`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await api.delete(`/projects/${project.id}`)
          ElMessage.success('删除项目成功')
          fetchProjects() // 重新加载项目列表
        } catch (error) {
          ElMessage.error('删除项目失败: ' + error.message)
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    }

    onMounted(() => {
      console.log('ProjectList 组件已挂载 at:', new Date().toISOString())
      // 页面加载时立即获取项目列表
      // 使用nextTick确保在DOM更新后立即执行
      nextTick(() => {
        console.log('ProjectList nextTick 执行 at:', new Date().toISOString())
        fetchProjects()
      })
    })

    return {
      projects,
      loading,
      goToCreateProject,
      viewProject,
      handleProjectAction,
      deleteProject,
      formatDate
    }
  }
}
</script>

<style scoped>
.project-list-container {
  width: 100%;
  margin: 0;
  padding: 0;
  background-color: #f9f6e7;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f0ebe0;
  border-bottom: 1px solid #e0d4b4;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #5a4a3a;
}

.create-project-btn {
  background: linear-gradient(135deg, #cdaa52, #b8943d);
  border: none;
  color: white;
  box-shadow: 0 2px 6px rgba(205, 170, 82, 0.3);
}

.create-project-btn:hover {
  background: linear-gradient(135deg, #b8943d, #a37e2d);
  box-shadow: 0 4px 12px rgba(205, 170, 82, 0.4);
  transform: translateY(-2px);
}

.content {
  padding: 20px;
}

.projects-grid {
  width: 100%;
}

.project-col {
  margin-bottom: 20px;
}

.project-card {
  border-radius: 8px;
  border: 1px solid #e0d4b4;
  background: #fffdf8;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
}

.project-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.project-header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.default-avatar {
  background: linear-gradient(135deg, #cdaa52, #e8d8a8);
  color: white;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.project-info {
  flex: 1;
  min-width: 0;
}

.project-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #5a4a3a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-description {
  margin: 0;
  font-size: 13px;
  color: #7a6b5a;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
  flex: 1;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #7a6b5a;
}

.project-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f1f5f9;
  padding-top: 12px;
}

.more-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.project-card:hover .more-actions {
  opacity: 1;
}

.create-project-card {
  border: 2px dashed #cdaa52;
  background: #fffdf8;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
}

.create-project-card:hover {
  border-style: solid;
  background: #fcfaf2;
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.create-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
  text-align: center;
}

.add-icon {
  font-size: 32px;
  color: #cdaa52;
  margin-bottom: 12px;
}

.create-card-content h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #5a4a3a;
}

.create-card-content p {
  margin: 0;
  font-size: 13px;
  color: #7a6b5a;
  line-height: 1.4;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 16px;
  }
  
  .content {
    padding: 16px;
  }
  
  .project-col {
    margin-bottom: 16px;
  }
  
  .project-header {
    gap: 10px;
  }
  
  .project-name {
    font-size: 15px;
  }
  
  .project-description {
    font-size: 12px;
  }
  
  .stat-item {
    font-size: 12px;
  }
}
</style>